<template>
  <div id="home">
    <nav-bar class="nav-bar">
      <div slot="center">购物街</div>
    </nav-bar>
    <tab-control v-show="isTabFixed" class="fixed" :titles="['流行','新款','精选']" @itemClick="tabClick"  ref="tab2"></tab-control>
    <scroll class="wrapper" ref="scroll" :probeType="2" :pullUpLoad="true" @pullingup="loadMore" @scroll="contentScroll">
      <div class="content">
        <!-- swipper轮番图 -->
        <home-swiper :banners="banners" @imgLoaded="imgLoaded"></home-swiper>
        <!-- 推荐 -->
        <recommend :recommends="recommends"></recommend>
        <!-- 流行 -->
        <featrue></featrue>
        <!-- tab控制组件 -->
        <tab-control :titles="['流行','新款','精选']" @itemClick="tabClick" ref="tab"></tab-control>
        <!-- 产品列表 -->

        <good-list :goodList="showGoodList" />


        <!-- 下拉加载更多提示 -->
        <div class="pullup-tips">
          <div v-if="!isPullUpLoad && !isEnd" class="before-trigger">
            <span class="pullup-txt">上拉加载更多...</span>
          </div>
          <div v-else-if="isPullUpLoad && !isEnd" class="after-trigger">
            <span class="pullup-txt">加载中...</span>
          </div>
          <div v-else class="after-trigger">
            <span class="pullup-txt">已加载全部数据</span>
          </div>
        </div>

      </div>
    </scroll>
    <back-top @backTop="backTop" v-show="isBackTopShow" />
  </div>
</template>

<script scoped>
//组件
import NavBar from "common/navbar/NavBar";
import HomeSwiper from "./childComps/HomeSwiper";
import Recommend from "./childComps/Recommend";
import Featrue from "./childComps/Featrue";
import TabControl from "common/tabControl/TabControl";
import GoodList from "./childComps/GoodList"
import Scroll from "common/scroll/Scroll"
import BackTop from "content/backTop/BackTop"

// 数据源
import { getHomeMultidata, getHomeData } from "network/home";
import {POP,NEW,SELL,BACKTOP_DISTENCE} from "@/utils/constant"
import {imgListenerMixin} from 'utils/mixin'
export default {
  name: "Home",
  data() {
    return {
      banners: [],
      recommends: [],
      currentType: POP,
      goodList: {
        'pop': {page:1, list: [], isEnd: false, scrollTop: 0},
        'new': {page:1, list: [], isEnd: false, scrollTop: 0},
        'sell': {page:1, list: [], isEnd: false, scrollTop: 0},
      },
      isEnd: false,
      isPullUpLoad: false,
      tabOffsetTop: 0 ,
      isTabFixed: false,
      isBackTopShow: false,
      saveY: 0,
      imgListener: null
    };
  },
  // mixins: [imgListenerMixin],
  components: {
    NavBar,
    HomeSwiper,
    Recommend,
    Featrue,
    TabControl,
    GoodList,
    Scroll,
    BackTop
  },
  created() {
    //请求banner及recommends数据
    this.getMultidata();
    //请求商品数据
    this.getHomeProducts(POP)
    this.getHomeProducts(NEW)
    this.getHomeProducts(SELL)

  },
  mounted() {
    this.$refs.scroll.refresh()
    //监听中央事件总线imgloaed
    let newRefresh = this._.debounce(this.$refs.scroll.refresh,100)
    this.imgListener = () => {
      newRefresh()
    }
    this.$bus.$on('imgloaed',this.imgListener)
  },
  computed: {
    showGoodList() {
      return this.goodList[this.currentType].list
    }
  },
  methods: {
    //网络请求数据
    getMultidata() {
      // let res =await getHomeMultidata();//{data: {…}, returnCode: "SUCCESS", success: true}
      getHomeMultidata().then(res => {
        console.log(res);
        this.banners = res.data.banner.list;
        this.recommends = res.data.recommend.list;
        //获得tab-control的offsetTop值
        this.$nextTick(() => {
          //console.log(this.$refs.tab.$el);
          // this.tabOffsetTop = this.$refs.tab.$el.offsetTop
          console.log(this.tabOffsetTop);
        })
      });
    },
    getHomeProducts(type){
      getHomeData(type,this.goodList[type].page).then(res => {
        let goodList = res.data.list
        console.log(res);
        //全部数据已经加载完成
        let page = this.goodList[type].page
        let isEnd = res.data.isEnd //通过isEnd判断关闭pullup事件
        this.goodList[type].list.push(...goodList)
        this.goodList[type].isEnd = isEnd
        this.isEnd = isEnd
        console.log(isEnd);//后端的数据一直为false
        //手动模拟数据结束：
        if(type == 'pop' && page === 5) {
           this.isEnd = true
           this.goodList[type].isEnd = true
        }
        if(type == 'new' && page === 3) {
           this.isEnd = true
           this.goodList[type].isEnd = true
        }
        if(type == 'sell' && page === 4) {
           this.isEnd = true
           this.goodList[type].isEnd = true
        }
        if(!this.isEnd) {
          this.goodList[type].page += 1
          this.$refs.scroll.finishPullUp()
          this.$refs.scroll.refresh()
          this.isPullUpLoad = false
        }else {
          this.$refs.scroll.closePullUp()
        }




      })
    },
    //所有事件
    //点击tanControl
    tabClick(index) {
      this.$refs.tab.currentIndex = index
      this.$refs.tab2.currentIndex = index
      switch (index) {
        case 0:
          this.currentType = POP;
          break;
        case 1:
          this.currentType = NEW;
          break;
        case 2:
          this.currentType = SELL
          break
      }
      this.$refs.scroll.scrollTo(0,this.goodList[this.currentType].scrollTop,0)
    },
    //图片加载完
   imgLoaded() {
    this.tabOffsetTop = this.$refs.tab.$el.offsetTop
    let newRefresh=this._.debounce(this.$refs.scroll.refresh,100)
    newRefresh()
   },
   //上拉加载更多
   loadMore() {
    this.isPullUpLoad = true
    this.getHomeProducts(this.currentType)
   },
   //监听滚动事件
   contentScroll(pos) {
       // 1.决定tabFixed是否显示
        this.isTabFixed = pos.y < -this.tabOffsetTop
       //2.回到顶部组件是否显示
        this.isBackTopShow = pos.y < -BACKTOP_DISTENCE
       //3.保存此时的scrollTop值?????
         if(-pos.y < this.tabOffsetTop) {
         // console.log(-pos.y)
          this.goodList['pop'].scrollTop = this.goodList['new'].scrollTop = this.goodList['sell'].scrollTop = pos.y
        }else{
          this.goodList['pop'].scrollTop = this.goodList['new'].scrollTop = this.goodList['sell'].scrollTop = -this.tabOffsetTop
        }
       //4,监听isEnd 与 goodList[type].isEnd是否一致
       if(this.isEnd && !this.goodList[this.currentType].isEnd) {
          this.isEnd = false
          this.$refs.scroll.openPullUp()
       }
   },
   //回到顶部
   backTop() {
     this.$refs.scroll.scrollTo(0, 0, 500)
   }
  },
  activated() {
    // console.log('actived');
    this.$refs.scroll.scrollTo(0,this.saveY,0)
    this.$refs.scroll.refresh()
  },
  deactivated() {
    // console.log('deactived');
    this.$bus.$off('imgloaed',this.imgListener)
    this.saveY = this.$refs.scroll.getScrollY()
  }
};
</script>

<style lang='less'>
#home {
  height: 100vh;
  .nav-bar {
    background-color: #ff8198;
    font-weight: 700;
    color: #fff;
  }
  .fixed {
   position: relative;
  //  background-color: #fff;
    z-index: 10;
  }
  .van-swipe__indicator {
    width: 0.12rem;
    height: 0.12rem;
  }
  .wrapper{
    position: absolute;
    width: 100%;
    top: .88rem;
    height: calc(100% - 1rem - 0.88rem);
    overflow: hidden;
    z-index: 8;
    .content {
      .pullup-tips > div{
        height: 0.8rem;
        line-height: 0.8rem;
        background-color: rgb(248, 241, 241);
        text-align: center;
        color: #999;
      }
    }
  }

}
</style>
